<template>
  <div>
    <el-dialog
      :title="dialogInfo.isAdd ? '添加商品管理' : '编辑商品管理'"
      :visible.sync="dialogInfo.isShow"
      :before-close="cancel"
      @opened="createEditor"
    >
      <el-form :model="goodsInfo" :rules="rules" ref="goodsInfo">
        <el-form-item
          label="一级分类"
          :label-width="formLabelWidth"
          prop="first_cateid"
        >
          <el-select
            @change="changeCate(false)"
            v-model="goodsInfo.first_cateid"
            placeholder="请选择"
          >
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="二级分类"
          :label-width="formLabelWidth"
          prop="second_cateid"
        >
          <el-select v-model="goodsInfo.second_cateid" placeholder="请选择">
            <el-option
              v-for="item in secondCate"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="商品名称"
          :label-width="formLabelWidth"
          prop="goodsname"
        >
          <el-input v-model="goodsInfo.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="商品价格"
          :label-width="formLabelWidth"
          prop="price"
        >
          <el-input v-model="goodsInfo.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="市场价格"
          :label-width="formLabelWidth"
          prop="market_price"
        >
          <el-input
            v-model="goodsInfo.market_price"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="onPreview"
            :on-remove="handleRemove"
            :auto-upload="false"
            :on-change="onChange"
            :file-list="fileList"
            :limit="1"
            :on-exceed="onExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item
          label="商品规格"
          :label-width="formLabelWidth"
          prop="specsid"
        >
          <el-select
            @change="changeSpecs(false)"
            v-model="goodsInfo.specsid"
            placeholder="请选择"
          >
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="规格属性"
          :label-width="formLabelWidth"
          prop="specsattr"
        >
          <el-select
            v-model="goodsInfo.specsattr"
            placeholder="请选择"
            multiple
          >
            <el-option
              v-for="item in specsArr"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-radio v-model="goodsInfo.isnew" :label="1">是</el-radio>
          <el-radio v-model="goodsInfo.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-radio v-model="goodsInfo.ishot" :label="1">是</el-radio>
          <el-radio v-model="goodsInfo.ishot" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="商品描述" :label-width="formLabelWidth">
          <div id="wangEditor"></div>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="goodsInfo.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="dialogInfo.isAdd" type="primary" @click="addGoods"
          >添 加</el-button
        >
        <el-button v-else type="primary" @click="editGoods">编 辑</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { postAddGoods, getGoodsInfo, getGoodsEdit } from "../../util/axios";
import { mapActions, mapGetters } from "vuex";
import E from "wangeditor";
export default {
  data() {
    return {
      goodsInfo: {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性
        isnew: 1, //是否新品1是2不是
        ishot: 1, //是否热卖1是2不是
        status: 1, //状态1正常2禁用
      },
      editor: null,
      secondCate: [],
      specsArr: [],
      formLabelWidth: "120px",
      dialogVisible: false,
      dialogImageUrl: "",
      imgUrl: "",
      fileList: [],
      rules: {
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "change" },
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" },
        ],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "change" },
        ],
        specsattr: [
          { required: true, message: "请选择规格属性", trigger: "blur" },
        ],
      },
    };
  },
  props: ["dialogInfo"],
  computed: {
    ...mapGetters({
      cateList: "cate/getCateList",
      specsList: "specs/getSpecsList",
    }),
  },
  mounted() {
    this.getCateList();
    this.getSpecsList();
  },
  methods: {
    createEditor() {
      this.editor = new E("#wangEditor");
      this.editor.create();
      this.editor.txt.html(this.goodsInfo.description);
    },
    onExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    onPreview(file) {
      console.log(file, "文件");
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      console.log(file, "移除", fileList);
    },
    onChange(file, fileList) {
      console.log(file, "文件详情，change时候");
      this.imgUrl = file.raw;
    },
    changeCate(n) {
      let index = this.cateList.findIndex(
        (item) => item.id == this.goodsInfo.first_cateid
      );
      this.secondCate = this.cateList[index].children;
      if (!n) {
        this.goodsInfo.second_cateid = "";
      }
    },
    changeSpecs(n) {
      let index = this.specsList.findIndex(
        (item) => item.id == this.goodsInfo.specsid
      );
      this.specsArr = this.specsList[index].attrs;
      if (!n) {
        this.goodsInfo.specsattr = [];
      }
    },
    ...mapActions({
      getSpecsList: "specs/getSpecsListAction",
      getCateList: "cate/getCateListAction",
      getCount: "goods/getGoodsCountAction",
      getGoodsList: "goods/getGoodsListAction",
    }),
    cancel() {
      this.$emit("cancel", false);
      this.reset();
    },
    reset() {
      (this.goodsInfo = {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性
        isnew: 1, //是否新品1是2不是
        ishot: 1, //是否热卖1是2不是
        status: 1, //状态1正常2禁用
      }),
      this.$refs.goodsInfo.resetFields();
    },
    changeSpecs(n) {
      let index = this.specsList.findIndex(
        (item) => item.id == this.goodsInfo.specsid
      );
      this.specsArr = this.specsList[index].attrs;
      if (!n) {
        this.goodsInfo.specsattr = [];
      }
    },
    addGoods() {
      this.$refs.goodsInfo.validate((valid) => {
        if (valid) {
          this.goodsInfo.specsattr = this.goodsInfo.specsattr.join(",");
          this.goodsInfo.img = this.imgUrl;
          this.goodsInfo.description = this.editor.txt.html();
          let file = new FormData();
          for (let i in this.goodsInfo) {
            file.append(i, this.goodsInfo[i]);
          }
          postAddGoods(file).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.msg);
              this.cancel();
              this.getGoodsList();
              this.getCount();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        } else {
          this.$message.error("验证失败");
          return false;
        }
      });
    },
    lookup(id) {
      getGoodsInfo({ id }).then((res) => {
        if (res.data.code == 200) {
          console.log(res.data, "查找的数据");
          this.goodsInfo = res.data.list;
          this.fileList = this.goodsInfo.img
            ? [{ url: this.$imgUrl + this.goodsInfo.img }]
            : [];
          this.goodsInfo.specsattr = this.goodsInfo.specsattr
            ? this.goodsInfo.specsattr.split(",")
            : [];
          this.goodsInfo.id = id;
          this.changeCate(true);
          this.changeSpecs(true);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    editGoods() {
      this.$refs.goodsInfo.validate((valid) => {
        if (valid) {
          this.goodsInfo.specsattr = this.goodsInfo.specsattr.join(",");
          this.goodsInfo.img = this.imgUrl ? this.imgUrl : this.goodsInfo.img;
          this.goodsInfo.description = this.editor.txt.html();
          let file = new FormData();
          for (let i in this.goodsInfo) {
            file.append(i, this.goodsInfo[i]);
          }
          getGoodsEdit(file).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.msg);
              this.cancel();
              this.getGoodsList();
              this.getCount();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        } else {
          this.$message.error("验证失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="" scoped>
</style>
